<template>
  <el-dialog title="绩效题目设置" custom-class="email-dialog" :before-close="canClose" :fullscreen="true" :visible.sync="showEmail" :close-on-click-modal="false">
    <div slot="title" class="title">{{(replyType === '' || replyType === 'cg' || replyType === 'kh')? '新': replyType === 'hf'? '回复': '转发'}}邮件</div>
    <div class="email-content">
      <div class="row-1">
        <div class="left-label">
          <span class="left-name">收件人</span>
          <span class="iconclass" @click="openRecipient(true)"><i class="el-icon-circle-plus-outline"></i></span>
        </div>
        <div class="people-wrapper clearfix" style="cursor: text;" @click="$refs.receiveinput.focus();">
          <el-tooltip v-for="(item, idx) in receiveArr" :key="item.id" class="item" effect="light" :content="item.receiveAccount" placement="bottom">
            <div class="select-people-item">
              {{item.nickname}} <i class="el-icon-close" @click.stop="removeItem('receiveArr', idx)"></i>
            </div>
          </el-tooltip>
          <div class="people-suggest-input">
            <input type="text" ref="receiveinput" class="people-suggest" @keyup="peopleHandle($event,1)" @blur.stop="peopleHandle($event,1)" @focus.stop="showSelectTable(1)" v-model="receiveinput">
            <div class="input-suggest" v-if="selectTable1 && searchData1.length > 0">
              <div v-for="item in searchData1" @click.stop="selectSuggest(item,1)" :key="item.id" class="suggest-item">
                {{item.nickname}}({{item.receiveAccount}})
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="row-1">
        <div class="left-label">
          <span class="left-name">抄&nbsp;&nbsp;&nbsp;送</span>
          <span class="iconclass" @click="openRecipient(false)"><i class="el-icon-circle-plus-outline"></i></span>
        </div>
        <div class="people-wrapper clearfix" style="cursor: text;" @click="$refs.ccinput.focus();"> 
          <el-tooltip v-for="(item, idx) in ccArr" :key="item.id" class="item" effect="light" :content="item.receiveAccount" placement="bottom">
            <div class="select-people-item">
              {{item.nickname}} <i class="el-icon-close" @click="removeItem('ccArr', idx)"></i>
            </div>
          </el-tooltip>
          <div class="people-suggest-input">
            <input type="text" ref="ccinput" class="people-suggest" @keyup="peopleHandle($event,2)" @blur="peopleHandle($event,2)" @focus.stop="showSelectTable(2)"  v-model="ccinput">
            <div class="input-suggest" v-if="selectTable2 && searchData2.length > 0">
              <div v-for="item in searchData2" @click.stop="selectSuggest(item,2)" :key="item.id" class="suggest-item">
                {{item.nickname}}({{item.receiveAccount}})
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="row-1">
        <div class="left-label">
          <span class="left-name">主&nbsp;&nbsp;&nbsp;题</span>
        </div>
        <input type="text" v-model="emailForm.subject">
      </div>
      <div class="row-1">
        <div class="left-label">
          <span class="left-name">附&nbsp;&nbsp;&nbsp;件</span>
          <span class="iconclass" @click="$refs.uploadInput.click()"><i class="el-icon-circle-plus-outline"></i></span>
          <input ref="uploadInput" style="display:none;" type="file" @change="uploadFile($event)" multiple>
        </div>
        <div class="files-wrapper clearfix">
          <div class="file" v-for="(file, idx) in emailForm.fileList" :key="file.id">
            <div class="file-type"><img :src="getPic(file.name)" alt=""></div>
            <div class="file-info">
              <p>{{file.name}}</p>
              <p>{{file.size / 1000}}KB</p>
              <div class="file-action">
                <el-tooltip effect="light" content="删除" placement="bottom">
                  <i class="el-icon-close" @click="delFile(idx)"></i>
                </el-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="row-1" style="padding: 0;">
        <div ref="toolbar" class="editor-tool-bar"></div>
        <div class="sign">
          <el-dropdown trigger="click" @command="handleCommand">
            <span class="el-dropdown-link" style="display: inline-block;height: 32px;line-height: 32px;width: 80px;">
              插入签名
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="(sign,idx) in signList" :key="sign.id" :command="idx">{{sign.title}}<span><i class="el-icon-edit" @click.stop="handleCommand('edit', idx)" style="margin:0 5px;cursor: pointer"></i></span><span><i class="el-icon-delete" @click.stop="delSign(sign.id)" style="margin:0 5px;cursor: pointer"></i></span></el-dropdown-item>
              <el-dropdown-item command="add">添加签名</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <div class="email-editor" ref="editor"></div>
      <div class="footer-bar">
        <p v-if="replyType === 'ds'" style="display: inline-block;">
          <el-date-picker
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择定时发送时间"
          v-model="dsTime">
        </el-date-picker>
        </p>
        <div v-if="replyType !== 'ds'" @click="sendEmail">发送</div>
        <div v-if="replyType !== 'ds'" @click="fbSendEmail">一对一发送</div>
        <div v-if="replyType !== 'ds'" @click="openTimeDialog">定时发送</div>
        <div v-if="replyType !== 'ds'" @click="sendCGX">存草稿</div>
        <div v-if="replyType === 'ds'" @click="saveDs">保存</div>
        <div v-if="replyType === 'ds'" @click="showEmail = false;">关闭</div>
      </div>
    </div>
    <el-dialog width="575px" custom-class="address-dialog" :visible.sync="showRecipient" append-to-body :show-close="false">
      <div slot="title" class="address-dialog-header">
        通讯录<i class="el-icon-close" @click="showRecipient = false;"></i>
      </div>
      <div class="address-dialog-body">
        <div class="select-left">
          <div class="select-left-search">
            <i class="el-icon-search"></i>
            <input type="text" v-model="selectinput" @keydown="selectSearch">
          </div>
          <div class="select-left-search-result">
            <el-tooltip v-for="item in tableData" :key="item.id" class="item" effect="light" :content="item.receiveAccount" placement="bottom">
              <div class="select-left-search-result-item" @click="selectPeople(item)">{{item.nickname}}</div>
            </el-tooltip>
          </div>
          <div class="select-left-search-page">
            <i class="el-icon-d-arrow-left" @click="currentChangeHandle(1)"></i>
            <i class="el-icon-arrow-left" @click="currentChangeHandle(page -1)"></i>
            <span style="color: red;">{{page}}</span>/{{totalPage}}
            <i class="el-icon-arrow-right" @click="currentChangeHandle(page + 1)"></i>
            <i class="el-icon-d-arrow-right" @click="currentChangeHandle(totalPage)"></i>
          </div>
        </div>
        <div class="select-middle">
          <i class="el-icon-arrow-right"></i>
        </div>
        <div class="select-right">
          <div class="select-right-section">
            <div class="select-right-section-title" @click="showSection = !showSection">收件人({{receiveArrCache.length}})</div>
            <div class="select-right-section-content" :style="{'height': showSection? '352px': '0'}">
              <div class="select-right-section-content-item" v-for="(item, idx) in receiveArrCache" :key="item.id">
                {{item.nickname}}
                <i class="el-icon-close" @click="removeItem('receiveArrCache', idx)"></i>
              </div>
            </div>
          </div>
          <div class="select-right-section">
            <div class="select-right-section-title" @click="showSection = !showSection">抄送({{ccArrCache.length}})</div>
            <div class="select-right-section-content" :style="{'height': !showSection? '352px': '0'}">
              <div class="select-right-section-content-item" v-for="(item, idx) in ccArrCache" :key="item.id">
                {{item.nickname}}
                <i class="el-icon-close" @click="removeItem('ccArrCache', idx)"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="address-dialog-footer">
        <div @click="saveCache">确定</div>
        <div @click="showRecipient = false;">取消</div>
      </div>
    </el-dialog>
    <el-dialog title="定时发送设置" :visible.sync="showTimeDialog" :append-to-body="true" width="600px">
      <el-row :gutter="20" style="margin-bottom: 30px;padding-left:40px;">
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <i class="el-icon-connection"></i>
            发送类型
          </div>
        </el-col>
        <el-col :span="16">
          <el-radio v-model="timeForm.sendType" label="1">普通发送</el-radio>
          <el-radio v-model="timeForm.sendType" label="2">一对一发送</el-radio>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="padding-left:40px;">
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <i class="el-icon-connection"></i>
            发送时间
          </div>
        </el-col>
        <el-col :span="16">
          <el-date-picker
            v-model="timeForm.sendTime"
            type="datetime"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showTimeDialog = false">取消</el-button>
        <el-button type="primary" @click="sendTimeEmail">保存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="签名设置"  custom-class="address-dialog" :visible.sync="showSignDialog" :close-on-click-modal="false" :show-close="false" :append-to-body="true" width="900px">
     <div slot="title" class="address-dialog-header">
        {{signForm.id? '编辑签名': '新增签名'}}<i class="el-icon-close" @click="showSignDialog = false;"></i>
      </div>
      <div class="sign-dialog-body">
        <div class="row-1">签名标题 <input v-model="signForm.title" type="text"></div>
        <div class="row-2">
          <div ref="toolbar2" class="editor-tool-bar"></div>
        </div>
        <div class="row-3">
          <div class="email-editor" ref="editor2"></div>
        </div>
      </div>
      <div class="address-dialog-footer" style="padding-left: 635px;">
        <div @click="saveSign">确定</div>
        <div @click="showSignDialog = false;">取消</div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import sinaEmotions from '@/assets/emotion/sina'
import formUtil from "@/utils/formUtil";
import {Loading, Message} from 'element-ui'
import {dateUtil} from '@/utils/dateUtil'

export default {
  data() {
    return {
      showSignDialog: false,
      showTimeDialog: false,
      showSection: true,
      showEmail: false,
      showRecipient: false,
      isInit: false,
      emailForm: {
        subject: '',
        accountId: '',
        receive: '',
        cc: '',
        fileList: [],
        replyMessageId: ''
      },
      timeForm: {
        sendType: '1',
        sendTime: ''
      },
      signForm: {
        id: '',
        content: '',
        title: ''
      },
      page: 1,
      tableData: [],
      totalPage: 1,
      pageSize: 10,
      receiveAccount: '',
      receiveArr: [],
      receiveArrCache: [],
      ccArr: [],
      ccArrCache: [],
      receiveinput: '',
      ccinput: '',
      searchData1: [],
      searchData2: [],
      threadId: null,
      selectTable1: false,
      selectTable2: false,
      replyType: '',
      needSaveEmatil: false,
      khName: '',
      selectinput: '',
      dsTime: '',
      dsDetailCache: {},
      signIsInit: false,
      editor: '',
      editor2: '',
      signList: [],
      myEmail: ''
    }
  },
  props: ['emailType'],
  async mounted() {
    let emailData = await this.$httpN.postB('crm/mail/account/list',{
      page: this.page,
      limit: this.pageSize,
    })

    if(emailData.length > 0) {
      let chosen = emailData.filter((item) => item.chosen);
      this.myEmail = chosen[0].account;
    }
  },
  methods:{
    handleCommand(command, idx) {
      if(command === 'add' || command === 'edit') {
        this.showSignDialog = true;
        if(!this.signIsInit) {
          this.$nextTick(async () => {
            let E = window.wangEditor;
            if(this.$refs.editor2) {
              var editor = new E(this.$refs.toolbar2, this.$refs.editor2)
              editor.customConfig.uploadImgServer = this.$http.adornUrl('/fileUpload');
              editor.customConfig.uploadImgHeaders = {'token': this.$cookie.get('token')}
              editor.customConfig.uploadFileName = 'file'
              editor.customConfig.pasteTextHandle = function (content) {
                let handleData = content;
                //清除无用标签
                handleData = handleData.replace(/<(meta|script|link|html|head|)[^>]*>/, '');
                handleData = handleData.replace(/<\/(meta|script|link|html|head)[^>]*>/, '');
                handleData = handleData.replace(/<head>[\s\S]*<body lang=ZH-CN>/, '');
                handleData = handleData.replace(/style\s*?=\s*?(['"])[\s\S]*?\1/g, '');
                handleData = handleData.replace(/\sclass\s?=\s?\w*/g, '');
                handleData = handleData.replace(/<span\s*?lang=EN-US\s*?><o:p><\/o\:p><\/span>/g, '');
                handleData = handleData.replace(/lang=EN-US/g, '');
                handleData = handleData.replace(/\n/g, '');
                return handleData
              }
              editor.customConfig.menus = ['head','bold','fontSize','fontName','table', 'italic','underline','strikeThrough','foreColor','backColor','link','justify','quote','emoticon','image','video','code','undo','redo']
              editor.customConfig.uploadImgHooks = {
                customInsert: function (insertImg, result, editor) {
                  var url = result.url + '?x-oss-process=style/forbid'
                  insertImg(url)
                }
              }
              this.signIsInit = true;
              editor.customConfig.emotions = [{title:'默认',type: 'image',content: sinaEmotions}];
              editor.create();
              this.editor2 = editor;

              if(command === 'add') {
                this.signForm = {
                  id: '',
                  content: '',
                  title: ''
                };
                this.editor2.txt.clear();
              }
              if(command === 'edit') {
                this.signForm = this.signList[idx];
                this.editor2.txt.html(this.signList[idx].content)
              }
            }
          })
        }else{
          if(command === 'add') {
            this.signForm = {
              id: '',
              content: '',
              title: ''
            };
            this.editor2.txt.clear();
          }
          if(command === 'edit') {
            this.signForm = this.signList[idx];
            this.editor2.txt.html(this.signList[idx].content)
          }
        }
      }else {
        this.editor.cmd.do('insertHTML', this.signList[command].content);
      }
    },
    async delSign(id) {
      formUtil.submitConfirm('您确定要删除签名吗？', async ()=> {
        if(!await this.$httpN.postB('crm/mail/sign/delete', [id], false)) return;
        formUtil.submitSuccess('删除');
        this.signList = await this.$httpN.get('crm/mail/sign/sign');
      })
    },
    async saveSign() {
      if(!this.signForm.title) return formUtil.submitError('请输入签名标题');
      this.signForm.content = this.editor2.txt.html();
      if(!await this.$httpN.postB('crm/mail/sign/save', this.signForm)) return;
      formUtil.submitSuccess('保存成功');
      this.showSignDialog = false;
      this.signList = await this.$httpN.get('crm/mail/sign/sign');
    },
    showSelectTable(type) {
      this['selectTable' + type] = true;
    },
    openTimeDialog() {
      this.showTimeDialog = true;
      this.timeForm = {
        sendType: '1',
        sendTime: ''
      }
    },
    selectSuggest(item, type) {
      let inputKey = type === 1? 'receiveinput': 'ccinput';
      let inputArrKey = type === 1? 'receiveArr': 'ccArr';
      if(this.checkEmailExist(this[inputArrKey], item.receiveAccount)) {
        this.$message.error('该邮件已在列表中');
        this[inputKey] = '';
        this['searchData' + type] = [];
        this['selectTable' + type] = false;
        return 
      }
      this[inputArrKey].push(item);
      this[inputKey] = '';
      this['searchData' + type] = [];
      this['selectTable' + type] = false;
    },
    async peopleHandle($event, type) {
      let inputKey = type === 1? 'receiveinput': 'ccinput';
      let inputArrKey = type === 1? 'receiveArr': 'ccArr';
      let inputValue = this[inputKey];
      //失去焦点自动生成
      if(($event.type === 'blur' && this['searchData' + type].length === 0 && inputValue) || ($event.type === 'keydown' && inputValue && $event.key === 'Enter')) {
        if(this.checkEmailExist(this[inputArrKey], inputValue)) {
          return this.$message.error('该邮件已在列表中');
        }
        this[inputArrKey].push({
          id: new Date().getTime(),
          nickname: inputValue,
          receiveAccount: inputValue
        })
        this[inputKey] = '';
      }
      
      if(($event.type === 'keyup' && inputValue && $event.key !== 'Enter' && inputValue.length > 2)) {
        clearTimeout(this.threadId)
        this.threadId = setTimeout(async () => {
          this['searchData' + type] = await this.$httpN.postB('crm/mail/addressee/getByCustomer', {search: inputValue});
        }, 500)
      }

      if($event.type === 'blur') {
        setTimeout(() => {
          this['selectTable' + type] = false;
        }, 100)
      }
    },
    selectSearch() {
      if(this.selectinput !== '') {
        clearTimeout(this.threadId)
        this.threadId = setTimeout(async () => {
          this.tableData = await this.$httpN.postB('crm/mail/addressee/getByCustomer', {search: this.selectinput});
        }, 300)
      }else {
        this.searchItem(true);
      }
    },
    checkEmailExist(target, email) {
      let isExit = target.filter((member) => member.receiveAccount === email);
      return isExit.length !== 0
    },
    async openEmail(emailDetail, type) {
      this.showEmail = true;
      if(!this.isInit) {
        this.$nextTick(async () => {
          this.signList = await this.$httpN.get('crm/mail/sign/sign');
          let E = window.wangEditor;
          this.isInit = true;
          if(this.$refs.editor) {
            var editor = new E(this.$refs.toolbar, this.$refs.editor)
            editor.customConfig.uploadImgServer = this.$http.adornUrl('/fileUpload');
            editor.customConfig.uploadImgHeaders = {'token': this.$cookie.get('token')}
            editor.customConfig.uploadFileName = 'file'
            editor.customConfig.pasteTextHandle = function (content) {
              let handleData = content;
              //清除无用标签
              handleData = handleData.replace(/<(meta|script|link|html|head|)[^>]*>/, '');
              handleData = handleData.replace(/<\/(meta|script|link|html|head)[^>]*>/, '');
              handleData = handleData.replace(/<head>[\s\S]*<body lang=ZH-CN>/, '');
              handleData = handleData.replace(/style\s*?=\s*?(['"])[\s\S]*?\1/g, '');
              handleData = handleData.replace(/\sclass\s?=\s?\w*/g, '');
              handleData = handleData.replace(/<span\s*?lang=EN-US\s*?><o:p><\/o\:p><\/span>/g, '');
              handleData = handleData.replace(/lang=EN-US/g, '');
              handleData = handleData.replace(/\n/g, '');
              return handleData
            }
            editor.customConfig.menus = ['head','bold','fontSize','fontName','table', 'italic','underline','strikeThrough','foreColor','backColor','link','justify','quote','emoticon','image','video','code','undo','redo']
            editor.customConfig.uploadImgHooks = {
              customInsert: function (insertImg, result, editor) {
                var url = result.url + '?x-oss-process=style/forbid'
                insertImg(url)
              }
            }
            editor.customConfig.emotions = [{title:'默认',type: 'image',content: sinaEmotions}];
            editor.create();
            this.editor = editor;
            if(emailDetail) {
              this.initEmail(emailDetail, type);
            }
          }
        })
      }else {
        this.receiveinput = '';
        this.ccinput = '';
        this.emailForm = {
          subject: '',
          accountId: '',
          receive: '',
          cc: '',
          replyMessageId: '',
          fileList: []
        };
        this.receiveArr = [];
        this.ccArr = [];
        if(!emailDetail) {
          this.editor.txt.clear();
          this.replyType = '';
        }else {
          this.initEmail(emailDetail, type)
        }
      }
    },
    async initEmail(emailDetail, type) {
      this.replyType = type;
      this.emailForm.subject = emailDetail.subject;
      if(emailDetail.content) {
        this.editor.txt.html(emailDetail.content);
      }else {
        this.editor.txt.clear();
      }
      if(type === 'hf') {
        this.emailForm.replyMessageId = emailDetail.id;
        let targetEmail = emailDetail.addressor.match(/(?!<)([^<>])+(?=>)/g)[0];
        let result = await this.$httpN.postB('crm/mail/addressee/getAddressee', {receiveAccount: targetEmail});
        if(result.length > 0) {
          this.receiveArr.push(result[0])
        }else {
          this.receiveArr.push({
            id: new Date().getTime(),
            nickname: targetEmail,
            receiveAccount: targetEmail
          })
        }
      }else if(type === 'qbhf'){
        this.emailForm.replyMessageId = emailDetail.id;

        let targetEmail3 = emailDetail.addressor.match(/(?!<)([^<>])+(?=>)/g)[0];
        let result = await this.$httpN.postB('crm/mail/addressee/getAddressee', {receiveAccount: targetEmail3});
        if(result.length > 0) {
          this.receiveArr.push(result[0])
        }else {
          this.receiveArr.push({
            id: new Date().getTime(),
            nickname: targetEmail3,
            receiveAccount: targetEmail3
          })
        }

        let targetEmail = emailDetail.receive.match(/(?!<)([^<>])+(?=>)/g);
        if(targetEmail && targetEmail.length > 0) {
          targetEmail.forEach(async (item) => {
            if(item === this.myEmail) return
            let result = await this.$httpN.postB('crm/mail/addressee/getAddressee', {receiveAccount: item});
            if(result.length > 0) {
              this.receiveArr.push(result[0])
            }else {
              this.receiveArr.push({
                id: new Date().getTime(),
                nickname: item,
                receiveAccount: item
              })
            }
          })
        }

        let targetEmail2 = emailDetail.cc.match(/(?!<)([^<>])+(?=>)/g);
        if(targetEmail2 && targetEmail2.length > 0) {
          targetEmail2.forEach(async (item) => {
            if(item === this.myEmail) return
            let result = await this.$httpN.postB('crm/mail/addressee/getAddressee', {receiveAccount: item});
            if(result.length > 0) {
              this.ccArr.push(result[0])
            }else {
              this.ccArr.push({
                id: new Date().getTime(),
                nickname: item,
                receiveAccount: item
              })
            }
          })
        }
      }else if(type === 'ds'){
        this.dsDetailCache = formUtil.deepCopy(emailDetail);
        this.dsTime = this.dsDetailCache.sendTime + ' ' + this.dsDetailCache.sendTimeDetail;
        let targetEmail = emailDetail.receive ?emailDetail.receive.split(';'): '';
        if(targetEmail && targetEmail.length > 0) {
          targetEmail.forEach(async (item) => {
            let result = await this.$httpN.postB('crm/mail/addressee/getAddressee', {receiveAccount: item});
            if(result.length > 0) {
              this.receiveArr.push(result[0])
            }else {
              this.receiveArr.push({
                id: new Date().getTime(),
                nickname: item,
                receiveAccount: item
              })
            }
          })
        }

        let targetEmail2 = emailDetail.cc? emailDetail.cc.split(';'): '';
        if(targetEmail2 && targetEmail2.length > 0) {
          targetEmail2.forEach(async (item) => {
            let result = await this.$httpN.postB('crm/mail/addressee/getAddressee', {receiveAccount: item});
            if(result.length > 0) {
              this.ccArr.push(result[0])
            }else {
              this.ccArr.push({
                id: new Date().getTime(),
                nickname: item,
                receiveAccount: item
              })
            }
          })
        }
        this.fetchFile(emailDetail.fileList);
      }else if(type === 'zf'){
        this.emailForm.replyMessageId = emailDetail.id;
      }else if(type === 'kh'){
        this.khName = emailDetail.name;
        let result = await this.$httpN.postQ('crm/mail/addressee/getByCustomerId', {customerId: emailDetail.name});
        if(result.length > 0) {
          this.receiveArr.push(result[0]);
        }
      }else if(type === 'cg') {
        this.emailForm.replyMessageId = emailDetail.id;
        let targetEmail = emailDetail.receive.match(/(?!<)([^<>])+(?=>)/g);
        if(targetEmail && targetEmail.length > 0) {
          targetEmail.forEach(async (item) => {
            let result = await this.$httpN.postB('crm/mail/addressee/getAddressee', {receiveAccount: item});
            if(result.length > 0) {
              this.receiveArr.push(result[0])
            }else {
              this.receiveArr.push({
                id: new Date().getTime(),
                nickname: item,
                receiveAccount: item
              })
            }
          })
        }

        let targetEmail2 = emailDetail.cc.match(/(?!<)([^<>])+(?=>)/g);
        if(targetEmail2 && targetEmail2.length > 0) {
          targetEmail2.forEach(async (item) => {
            let result = await this.$httpN.postB('crm/mail/addressee/getAddressee', {receiveAccount: item});
            if(result.length > 0) {
              this.ccArr.push(result[0])
            }else {
              this.ccArr.push({
                id: new Date().getTime(),
                nickname: item,
                receiveAccount: item
              })
            }
          })
        }
        this.fetchFile(emailDetail.fileList);
      }else if(type === 'zcbj') {
        let targetEmail = emailDetail.receive.match(/(?!<)([^<>])+(?=>)/g);
        if(targetEmail && targetEmail.length > 0) {
          targetEmail.forEach(async (item) => {
            let result = await this.$httpN.postB('crm/mail/addressee/getAddressee', {receiveAccount: item});
            if(result.length > 0) {
              this.receiveArr.push(result[0])
            }else {
              this.receiveArr.push({
                id: new Date().getTime(),
                nickname: item,
                receiveAccount: item
              })
            }
          })
        }

        let targetEmail2 = emailDetail.cc.match(/(?!<)([^<>])+(?=>)/g);
        if(targetEmail2 && targetEmail2.length > 0) {
          targetEmail2.forEach(async (item) => {
            let result = await this.$httpN.postB('crm/mail/addressee/getAddressee', {receiveAccount: item});
            if(result.length > 0) {
              this.ccArr.push(result[0])
            }else {
              this.ccArr.push({
                id: new Date().getTime(),
                nickname: item,
                receiveAccount: item
              })
            }
          })
        }
        this.fetchFile(emailDetail.fileList);
      }else {
        let signList = await this.$httpN.get('crm/mail/sign/sign');
        if(signList.length > 0) {
          this.editor.txt.html(signList[0].content);
          var range = window.getSelection();
          range.selectAllChildren(this.editor.$textElem[0]); 
          range.collapseToStart(); 
          this.editor.$textElem[0].blur()
        }
        if(!emailDetail.receive) return;
        let targetEmail = emailDetail.receive.match(/(?!<)([^<>])+(?=>)/g);
        targetEmail = [...new Set(targetEmail)]
        if(targetEmail && targetEmail.length > 0) {
          targetEmail.forEach(async (item) => {
            let result = await this.$httpN.postB('crm/mail/addressee/getAddressee', {receiveAccount: item});
            if(result.length > 0) {
              this.receiveArr.push(result[0])
            }else {
              this.receiveArr.push({
                id: new Date().getTime(),
                nickname: item,
                receiveAccount: item
              })
            }
          })
        }
      }
    },
    fetchFile(fileArr) {
      let that = this;
      fileArr.forEach((file) => {
        var x = new XMLHttpRequest();
        x.open("GET", file.fileUrl, true);
        x.responseType = 'blob';
        x.onload=function(e) {
          let downloadFile = new File([x.response], file.fileName);
          that.emailForm.fileList.push(downloadFile)
        }
        x.send();
      })
    },
    getPic(filename) {
      if(filename) {
        if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438103037435905.png'
        }else if(/\.(txt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438530785140737.png'
        }else if(/\.(xls|xlsx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438725690253314.png'
        }else if(/\.(doc|docx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439195636850689.png'
        }else if(/\.(psd)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439984203751426.png'
        }else if(/\.(pdf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440139145535490.png'
        }else if(/\.(ppt|pptx|dps|dpt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440657859305473.png'
        }else if(/\.(rar|zip|arj|gz)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442063039193090.png'
        }else if(/\.(html|htm)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442135319633921.png'
        }else if(/\.(dwg|bak|dwt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276441741667459074.png'
        }else if(/\.(wav|aif|au|mp3|ram|wma|mmf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442006684524546.png'
        }else if(/\.(avi|mov|rmvb|rm|flv|mp4)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442233483124737.png'
        }else{
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
        }
      }else {
        return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
      }
    },
    saveCache() {
      this.receiveArr = formUtil.deepCopy(this.receiveArrCache);
      this.ccArr = formUtil.deepCopy(this.ccArrCache);
      this.showRecipient = false;
    },
    selectPeople(item) {
      if(this.showSection) {
        let isExit = this.receiveArrCache.filter((member) => member.receiveAccount === item.receiveAccount);
        if(isExit.length === 0) this.receiveArrCache.push(item);
      }else {
        let isExit = this.ccArrCache.filter((member) => member.receiveAccount === item.receiveAccount);
        if(isExit.length === 0) this.ccArrCache.push(item);
      }
    },
    removeItem(target, idx) {
      this[target].splice(idx, 1);
    },
    async openRecipient(type) {
      this.searchItem(true)
      this.showRecipient = true;
      this.showSection = type;
      this.receiveArrCache = formUtil.deepCopy(this.receiveArr);
      this.ccArrCache = formUtil.deepCopy(this.ccArr);
    },
    currentChangeHandle(page) {
      if(page > this.totalPage || page < 1) return; 
      this.page = page;
      this.searchItem();
    },
    async searchItem(init) {
      if(init) this.page = 1;
      let data = await this.$httpN.postB('crm/mail/addressee/list',{
        receiveAccount: this.receiveAccount,
        page: this.page,
        limit: this.pageSize,
      })
      this.tableData = data.list;
      this.totalPage = data.totalPage;
    },
    delFile(idx){
      this.emailForm.fileList.splice(idx, 1)
    },
    async uploadFile(e) {
      this.emailForm.fileList.push(...e.target.files)
    },
    async sendEmail() {
      let that = this;
      this.emailForm.receive = this.receiveArr.map((item) => item.receiveAccount).join(';');
      this.emailForm.cc = this.ccArr.map((item) => item.receiveAccount).join(';');
      this.emailForm.content = this.editor.txt.html();
      var formData = new FormData();
      this.emailForm.fileList.forEach((file) => {
        formData.append("fileList", file, file.name);
      })
      formData.append("receive", this.emailForm.receive);
      formData.append("cc", this.emailForm.cc);
      formData.append("content", this.emailForm.content);
      formData.append("subject", this.emailForm.subject);
      if(this.replyType === 'hf' || this.replyType === 'qbhf') formData.append("replyMessageId", this.emailForm.replyMessageId);
      if(this.replyType === 'zf') formData.append("messageId", this.emailForm.replyMessageId);
      if(this.replyType === 'cg') formData.append("draftMessageId", this.emailForm.replyMessageId);
      if(this.replyType === 'cg') formData.append("fromDraft", true);
      if(!await this.$httpN.uploadNew(this.replyType === 'zf' ?'crm/mail/message/transmit': 'crm/mail/message/send', formData)) return;
      formUtil.submitSuccess('发送成功');
      if(this.replyType === 'kh') return this.showEmail = false;
      let loadingControl = Loading.service({fullscreen: true,background: 'rgba(0, 0, 0, 0.7)',text: '加载中...'});
      this.showEmail = false;
      setTimeout(() => {
        this.$parent.getListData(true)
        loadingControl.close();
      }, 2500);
    },
    async saveDs() {
      this.emailForm.receive = this.receiveArr.map((item) => item.receiveAccount).join(';');
      this.emailForm.cc = this.ccArr.map((item) => item.receiveAccount).join(';');
      this.emailForm.content = this.editor.txt.html();
      var formData = new FormData();
      this.emailForm.fileList.forEach((file) => {
        formData.append("fileList", file, file.name);
      })
      formData.append("receive", this.emailForm.receive);
      formData.append("cc", this.emailForm.cc);
      formData.append("content", this.emailForm.content);
      formData.append("subject", this.emailForm.subject);
      formData.append("sendType", this.dsDetailCache.sendType);
      formData.append("sendTime", this.dsTime);
      
      if(this.dsDetailCache.replyMessageId) formData.append("replyMessageId", this.dsDetailCache.replyMessageId);
      if(this.dsDetailCache.messageId) formData.append("messageId", this.dsDetailCache.messageId);
      if(this.dsDetailCache.draftMessageId) formData.append("draftMessageId", this.dsDetailCache.draftMessageId);
      if(this.dsDetailCache.fromDraft) formData.append("fromDraft", this.dsDetailCache.fromDraft);
      if(this.dsDetailCache.id) formData.append("id", this.dsDetailCache.id);

      if(!await this.$httpN.uploadNew('crm/mail/messageTimer/save', formData)) return;
      formUtil.submitSuccess('定时任务修改成功');
      this.showEmail = false;
      this.$parent.getListData(true)
    },
    async sendTimeEmail() {
      this.emailForm.receive = this.receiveArr.map((item) => item.receiveAccount).join(';');
      this.emailForm.cc = this.ccArr.map((item) => item.receiveAccount).join(';');
      this.emailForm.content = this.editor.txt.html();
      var formData = new FormData();
      this.emailForm.fileList.forEach((file) => {
        formData.append("fileList", file, file.name);
      })
      formData.append("receive", this.emailForm.receive);
      formData.append("cc", this.emailForm.cc);
      formData.append("content", this.emailForm.content);
      formData.append("subject", this.emailForm.subject);
      formData.append("sendType", this.timeForm.sendType);
      formData.append("sendTime", new Date(this.timeForm.sendTime).Format(`yyyy-MM-dd hh:mm:ss`));
      if(this.replyType === 'hf' || this.replyType === 'qbhf') formData.append("replyMessageId", this.emailForm.replyMessageId);
      if(this.replyType === 'zf') formData.append("messageId", this.emailForm.replyMessageId);
      if(this.replyType === 'cg') formData.append("draftMessageId", this.emailForm.replyMessageId);
      if(this.replyType === 'cg') formData.append("fromDraft", true);
      if(!await this.$httpN.uploadNew('crm/mail/messageTimer/save', formData)) return;
      formUtil.submitSuccess('定时任务创建成功');
      this.showEmail = false;
      this.showTimeDialog = false;
      this.$parent.getListData(true)
    },
    async fbSendEmail() {
      this.emailForm.receive = this.receiveArr.map((item) => item.receiveAccount).join(';');
      this.emailForm.cc = this.ccArr.map((item) => item.receiveAccount).join(';');
      this.emailForm.content = this.editor.txt.html();
      var formData = new FormData();
      this.emailForm.fileList.forEach((file) => {
        formData.append("fileList", file, file.name);
      })
      formData.append("receive", this.emailForm.receive);
      formData.append("cc", this.emailForm.cc);
      formData.append("content", this.emailForm.content);
      formData.append("subject", this.emailForm.subject);
      if(this.replyType === 'hf' || this.replyType === 'qbhf') formData.append("replyMessageId", this.emailForm.replyMessageId);
      if(this.replyType === 'zf') formData.append("messageId", this.emailForm.replyMessageId);
      if(this.replyType === 'cg') formData.append("draftMessageId", this.emailForm.replyMessageId);
      if(this.replyType === 'cg') formData.append("fromDraft", true);
      if(!await this.$httpN.uploadNew('crm/mail/message/sendOne', formData)) return;
      if(this.replyType === 'kh') return this.showEmail = false;
      formUtil.submitSuccess('一对一发送邮箱需要较长时间，请稍后确认');
      this.showEmail = false;
      this.$parent.getListData(true)
    },
    async sendCGX() {
      this.emailForm.receive = this.receiveArr.map((item) => item.receiveAccount).join(';');
      this.emailForm.cc = this.ccArr.map((item) => item.receiveAccount).join(';');
      this.emailForm.content = this.editor.txt.html();
      var formData = new FormData();
      this.emailForm.fileList.forEach((file) => {
        formData.append("fileList", file, file.name);
      })
      formData.append("receive", this.emailForm.receive);
      formData.append("cc", this.emailForm.cc);
      formData.append("content", this.emailForm.content);
      formData.append("subject", this.emailForm.subject);
      if(this.replyType === 'hf' || this.replyType === 'qbhf') formData.append("replyMessageId", this.emailForm.replyMessageId);
      if(this.replyType === 'cg') formData.append("draftMessageId", this.emailForm.replyMessageId);
      if(!await this.$httpN.uploadNew('crm/mail/message/draft', formData)) return;
      formUtil.submitSuccess('保存成功');
      if(this.replyType === 'kh') return this.showEmail = false;
      let loadingControl = Loading.service({fullscreen: true,background: 'rgba(0, 0, 0, 0.7)',text: '加载中...'});
      this.showEmail = false;
      setTimeout(() => {
        this.$parent.getListData(true)
        loadingControl.close();
      }, 2500);
    },
    canClose(done) {
      formUtil.submitConfirm('是否在关闭前保存到草稿箱', async ()=> {
        this.sendCGX()
      }, '提示', () =>{
        done()
      })
    }
  }
}
</script>

<style lang="scss">
  .address-dialog{
    padding: 12px;
    .el-dialog__header{
     padding: 0;
    }
    .el-dialog__body{
      padding: 0;
    }
    .address-dialog-header{
      line-height: 40px;
      background-color: #efefef;
      color: #252629;
      padding: 0 40px 0 12px;
      position: relative;
      i{
        position: absolute;
        font-size: 18px;
        top: 10px;
        right: 10px;
        cursor: pointer;
        &:hover{
          background-color: #ccc;
          color: #444547;
        }
      }
    }
    .sign-dialog-body{
      padding: 10px;
      .row-1{
        margin-top: 10px;
        padding-left: 12px;
        input{
          margin-left:15px;
          height: 26px;
          line-height: 26px;
          border: 1px solid rgba(0,0,0,.06);
        }
      }
      .row-2{
        margin-top: 15px;
        border-bottom: 1px solid #ECECEC;
      }
      .row-3{
        border-bottom: 1px solid #ECECEC;
        height: 300px;
        .email-editor{
          height: 300px;
          .w-e-text table{
            border: none;
          }
          .w-e-text table td, .w-e-text table th{
            border: none;
          }
        }
      }
    }
    .address-dialog-body{
      display: flex;
      margin-top: 12px;
      height: 400px;
      .select-left{
        border: 1px solid rgba(0,0,0,.06);
        width: 300px;
        .select-left-search{
          height: 35px;
          border-bottom: 1px solid rgba(0,0,0,.06);
          padding: 6px 20px 6px 40px;
          position: relative;
          >i{
            position: absolute;
            font-size: 14px;
            top: 10px;
            left: 10px;
            cursor: pointer;
          }
          input{
            width: 100%;
            border: none;
            outline: none;
            height: 22px;
            line-height: 22px;
          }
        }
        .select-left-search-result{
          height:330px;
          .select-left-search-result-item{
            padding-left: 10px;
            line-height:24px;
            font-size: 12px;
            color: #252629;
            cursor: pointer;
            &:hover{
              background-color: #efefef;
            }
          }
        }
        .select-left-search-page{
          line-height: 31px;
          height: 31px;
          padding-left: 100px;
          border-top: 1px solid rgba(0,0,0,.06);
          >i{
            cursor: pointer;
          }
        }
      }
      .select-middle{
        width: 25px;
        position: relative;
        height: 100%;
        i{
          position: absolute;
          top: 0;
          bottom: 0;
          left: 0;
          right: 0;
          width: 16px;
          height: 16px;
          margin: auto;
          font-weight: bold;
          font-size: 18px;
        }
      }
      .select-right{
        width: 225px;
        border: 1px solid rgba(0,0,0,.06);
        background-color: #efefef;
        .select-right-section{
          .select-right-section-title{
            line-height: 22px;
            border-top: solid 1px rgba(0,0,0,.06);
            padding: 0 7px;
            font-size: 12px;
            color:#6f7072;
          }
          .select-right-section-content{
            height: 300px;
            border-top: solid 1px rgba(0,0,0,.06);
            transition:  all 0.2s;
            overflow: hidden;
            .select-right-section-content-item{
              padding: 0 24px 0 12px;
              line-height: 24px;
              font-size: 12px;
              position: relative;
              i{
                display: none;
                position: absolute;
                right: 4px;
                top: 4px;
                font-size: 16px;
                cursor: pointer;
              }
              &:hover{
                i{
                  display: block;
                }
              }
            }
          }
        }
      }
    }
    .address-dialog-footer{
      padding: 20px 0 10px 315px;
      >div{
        width: 100px;
        line-height: 32px;
        display: inline-block;
        text-align: center;
        margin-right: 15px;
        border-radius: 4px;
        cursor: pointer;
      }
      >div:first-child {
        background-color: #3a81fc;
        border: 1px solid #3a81fc;
        color: #FFF;
        border-radius: 4px;
        &:hover{
        background-color: #3577e9;
        border: 1px solid #3577e9;
        }
      }
      >div:last-child{
        border: 1px solid #ccc;
        &:hover{
          background-color: rgba(0,0,0,.08);
        }
      }
    }
  }
 .email-dialog{
   .el-dialog__header{
    padding: 0;
    .el-dialog__headerbtn{
      font-size: 35px;
    }
   }
   .el-dialog__body{
     padding: 0;
   }
   .title{
     text-align: center;
     font-size: 18px;
     line-height: 42px;
     font-weight: bold;
   }
   .email-content{
     margin-top: 12px;
     padding-bottom: 50px;
     .row-1{
       padding: 5px 130px 5px 132px;
       position: relative;
       min-height: 45px;
       border-bottom:1px solid rgba(0,0,0,.06);
       .left-label{
         position: absolute;
         left: 24px;
         top: 6px;
         font-size: 14px;
         color: rgb(37, 38, 41);
         line-height: 32px;
       }
       i{
         font-size: 16px;
       }
       .iconclass{
         display:inline-block;
         width: 32px;
         height: 32px;
         text-align: center;
         cursor: pointer;
         &:hover{
           background-color: rgba(0,0,0,.08);
         }
       }
       .left-name{
         display: inline-block;
         width: 50px;
       }
       input{
         outline: none;
         border: none;
         width: 100%;
         font-size: 14px;
         font-weight: 700;
         height: 34px;
         line-height: 34px;
       }
       .people-wrapper{
         padding: 5px 0;
         .select-people-item{
           cursor: pointer;
           float:left;
           line-height: 24px;
           padding: 0 10px;
           background-color: #b8d2fe;
           border-radius: 2px;
           font-size: 12px;
           color: #252629;
           margin-right: 5px;
           i{
             font-size: 12px;
             cursor: pointer;
             &:hover{
               background-color: #7aadfd;
             }
           }
         }
         .people-suggest{
           width: auto;
           line-height: 24px;
           height: 24px;
           font-weight: normal;
           margin-left: 10px;
         }
         .people-suggest-input{
           display: inline-block;
           position:relative;
         }
         .input-suggest{
           position: absolute;
           width:500px;
           height: 200px;
           bottom: -200px;
           left: 0;
           box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
           border: 1px solid #e4e7ed;
           background-color: #fff;
           z-index: 99;
           overflow: auto;
           cursor: initial;
           .suggest-item{
            padding: 0 20px;
            margin: 0;
            line-height: 34px;
            cursor: pointer;
            color: #606266;
            font-size: 14px;
            list-style: none;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            &:hover{
              background-color: #f5f7fa
            }
           }
         }
       }
       .files-wrapper{
         .file{
           float:left;
           display: flex;
           width: 268px;
           height: 56px;
           background: #efefef;
           border-radius: 2px;
           margin-right: 16px;
           margin-bottom: 5px;
           &:hover{
             .file-info .file-action{
               visibility: visible;
             }
           }
          .file-type{
            width: 56px;
            text-align: center;
            line-height: 56px;
            img{
              width: 32px;
              height: 32px;
              text-align: center;
            }
          }
          .file-info{
            position: relative;
            width: calc(100% - 56px);
            p{
              margin: 0;
              font-size: 12px;
              line-height: 16px;
            }
            >p:first-child{
              margin-top: 12px;
              color:black;
            }
            >p:last-child{
              color: #6f7072;
            }
            .file-action{
              position: absolute;
              width: 100%;
              height: 100%;
              top: 0;
              left: 0;
              visibility: hidden;
              background-color: #efefef;
              opacity: .9;
              filter: alpha(opacity=90);
              padding: 11px;
              text-align: right;
              line-height: 34px;
              i{
                font-size: 20px;
                margin-right: 5px;
                padding: 5px;
                cursor: pointer;
                &:hover{
                  background-color: rgba(0,0,0,.08);
                  color: #444547;
                }
              }
            }
          }
         }
       }
     }
     .editor-tool-bar{
      padding: 8px 15px;
     }
     .sign{
        position: absolute;
        top:6px;
        left:715px;
        width: 83px;
        height: 32px;
        line-height: 32px;
        font-weight: bold;
        text-align: center;
        color:#999;
        cursor: pointer;
        &::before{
          position: absolute;
          height:22px;
          width:1px;
          content: '';
          top:5px;
          left:-5px;
          background: #ECECEC;
        }
        &::after{
          position: absolute;
          height:22px;
          width:1px;
          content: '';
          top:5px;
          right:-5px;
          background: #ECECEC;
        }
        &:hover{
          background: rgba(0,0,0,.08);
        }
        .sign-content{
          display: none;
          width: 200px;
          box-shadow: 0 3px 4px 0 rgba(0,0,0,.06), 0 10px 24px 0 rgba(24,25,26,.26);
          background: #fff;
          border-radius: 3px;
          >div{
            line-height: 34px;
            border-bottom: 1px solid #ECECEC;
            padding: 2px 30px;
            text-align: left;
            font-weight: normal;
            color: black;
            cursor: pointer;
            &:hover{
              background: rgba(0,0,0,.08);
            }
          }
        }
     }
     .email-editor{
       padding: 15px 15px;
       .w-e-text{
         min-height: 300px;
       }
       .w-e-text table{
         border: none;
       }
       .w-e-text table td, .w-e-text table th{
         border: none;
       }
     }
     .footer-bar{
       position: fixed;
       bottom: 0;
       left:0;
       width: 100%;
       padding: 12px 24px 16px 24px;
       z-index: 2;
       background-color: #FFF;
       >div{
         width: 100px;
         line-height: 32px;
         display: inline-block;
         text-align: center;
         margin-right: 15px;
         border-radius: 4px;
         cursor: pointer;
         background-color: #3a81fc;
         border: 1px solid #3a81fc;
         color: #FFF;
         border-radius: 4px;
         &:hover{
          background-color: #3577e9;
          border: 1px solid #3577e9;
         }
       }
      
       >div:last-child{
         background-color: white;
         border: 1px solid #ccc;
         color: black;
         &:hover{

           background-color: rgba(0,0,0,.08);
         }
       }
     }
   }
 }
</style>